package com.skivingcloud.report.service.impl;

import com.skivingcloud.common.exceptions.BusinessException;
import com.skivingcloud.report.dto.DataSetTransformDto;
import com.skivingcloud.report.service.TransformStrategy;
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JsTransformServiceImpl implements TransformStrategy {
    private static final Logger log = LoggerFactory.getLogger(JsTransformServiceImpl.class);
    private ScriptEngine engine;
    {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript");
    }

    /**
     * 数据清洗转换 类型
     *
     * @return 类型-JS
     */
    @Override
    public String type() {
        return "js";
    }

    /***
     * 清洗转换算法接口
     * @param def 定义
     * @param data 数据
     * @return 转换结果
     */
    @Override
    public List<Map<String, Object>> transform(DataSetTransformDto def, List<Map<String, Object>> data) {
        return getValueFromJs(def,data);
    }

    private List<Map<String, Object>> getValueFromJs(DataSetTransformDto def, List<Map<String, Object>> data) {
        String js = def.getTransformScript();
        try {
            engine.eval(js);
            if(engine instanceof Invocable invocable){
                Object dataTransform = invocable.invokeFunction("dataTransform", data);
                if (dataTransform instanceof List) {
                    return (List<Map<String, Object>>) dataTransform;
                }
                //前端js自定义的数组[{"aa":"bb"}]解析后变成{"0":{"aa":"bb"}}
                ScriptObjectMirror scriptObjectMirror = (ScriptObjectMirror) dataTransform;
                List<Map<String, Object>> result = new ArrayList<>();
                scriptObjectMirror.forEach((key, value) -> {
                    ScriptObjectMirror valueObject = (ScriptObjectMirror) value;
                    Map<String, Object> jsonObject = new HashMap<>(valueObject);
                    result.add(jsonObject);
                });
                return result;
            }

        } catch (Exception ex) {
            log.info("执行js异常", ex);
            throw new BusinessException("执行js异常");
        }
        return null;
    }
}
